import React, { useState, useEffect } from 'react';
import {
  List,
  Button,
  Space,
  Popconfirm,
  Tag,
  Card,
  Row,
  Col,
  Statistic,
  Select,
  DatePicker,
  Form,
  Typography,
  Avatar,
  Image,
  Divider,
  Collapse,
  Pagination
} from 'antd';
import {
  DeleteOutlined,
  ReloadOutlined,
  BarChartOutlined,
  MessageOutlined,
  GiftOutlined,
  UserOutlined,
  ManOutlined,
  WomanOutlined,
  CrownOutlined,
  HeartOutlined,
  SearchOutlined,

} from '@ant-design/icons';
import { Message } from '../types/Message';
import { MessageFilters } from '../types/SharedTypes';

import { useMessages } from '../hooks/useMessages';
import { useRooms } from '../hooks/useRooms';
import { useSessions } from '../hooks/useSessions';
import { PAGINATION_CONFIG } from '../constants/api';
import { getPaginationSize } from '../utils/storage';
import dayjs from 'dayjs';

const { RangePicker } = DatePicker;
const { Option } = Select;
const { Text } = Typography;

const MessagePage: React.FC = () => {
  const { messages, loading, pagination, stats, fetchMessages, fetchMessageStats, deleteMessage } = useMessages();
  const { rooms, fetchRooms } = useRooms();
  const { sessions, loading: sessionsLoading, fetchSessions } = useSessions();
  const [form] = Form.useForm();
  const [filters, setFilters] = useState<MessageFilters>({});
  const [showStats, setShowStats] = useState(false);
  const [selectedRoomId, setSelectedRoomId] = useState<string | undefined>();
  const [searchCollapsed, setSearchCollapsed] = useState(false);

  // 消息类型选项
  const messageTypes = [
    { value: 'WebcastChatMessage', label: '聊天消息', color: 'blue' },
    { value: 'WebcastGiftMessage', label: '礼物消息', color: 'gold' },
    { value: 'WebcastLikeMessage', label: '点赞消息', color: 'red' },
    { value: 'WebcastMemberMessage', label: '进入消息', color: 'cyan' },
    { value: 'WebcastSocialMessage', label: '社交消息', color: 'purple' },
    { value: 'WebcastRoomUserSeqMessage', label: '用户序列消息', color: 'green' },
    { value: 'WebcastRoomStatsMessage', label: '房间统计消息', color: 'orange' },
    { value: 'WebcastRoomRankMessage', label: '房间排行消息', color: 'magenta' },
  ];

  // 获取消息类型标签
  const getMessageTypeTag = (type: string) => {
    const typeConfig = messageTypes.find(t => t.value === type);
    return (
      <Tag color={typeConfig?.color || 'default'}>
        {typeConfig?.label || type}
      </Tag>
    );
  };

  // 处理房间选择变化
  const handleRoomChange = (roomId: string) => {
    setSelectedRoomId(roomId);
    // 清空session选择
    form.setFieldsValue({ sessionId: undefined });
    // 获取该房间的sessions
    if (roomId) {
      fetchSessions(roomId);
    }
    // 自动触发搜索
    handleFormChange();
  };

  // 处理表单值变化，自动触发搜索
  const handleFormChange = async () => {
    try {
      const values = await form.validateFields();
      const newFilters: MessageFilters = {
        ...values,
        page: 1,
        limit: getPaginationSize(PAGINATION_CONFIG.DEFAULT_PAGE_SIZE),
      };

      if (values.dateRange) {
        newFilters.startTime = values.dateRange[0].format('YYYY-MM-DD HH:mm:ss');
        newFilters.endTime = values.dateRange[1].format('YYYY-MM-DD HH:mm:ss');
      }

      setFilters(newFilters);
      await fetchMessages(newFilters);
      
      if (showStats) {
        await fetchMessageStats(newFilters);
      }
    } catch (error) {
      // 表单验证失败时不执行搜索
    }
  };

  // 重置搜索
  const handleReset = async () => {
    form.resetFields();
    setSelectedRoomId(undefined);
    const newFilters: MessageFilters = { page: 1, limit: getPaginationSize(PAGINATION_CONFIG.DEFAULT_PAGE_SIZE) };
    setFilters(newFilters);
    await fetchMessages(newFilters);
    
    if (showStats) {
      await fetchMessageStats({});
    }
  };

  // 切换统计显示
  const toggleStats = async () => {
    const newShowStats = !showStats;
    setShowStats(newShowStats);
    
    if (newShowStats && !stats) {
      await fetchMessageStats(filters);
    }
  };

  // 处理分页变化
  const handleTableChange = async (page: number, pageSize?: number) => {
    const newFilters = { 
      ...filters, 
      page, 
      limit: pageSize || pagination?.pageSize || getPaginationSize(PAGINATION_CONFIG.DEFAULT_PAGE_SIZE) 
    };
    setFilters(newFilters);
    await fetchMessages(newFilters);
  };
  
  // 处理分页大小变化
  const handlePageSizeChange = async (current: number, size: number) => {
 
    const newFilters = { 
      ...filters, 
      page: current,
      limit: size 
    };
    setFilters(newFilters);
    await fetchMessages(newFilters);
  };

  // 删除消息
  const handleDelete = async (messageId: string) => {
    const success = await deleteMessage(messageId);
    if (success && showStats) {
      await fetchMessageStats(filters);
    }
  };

  // 获取性别图标
  const getGenderIcon = (gender?: number) => {
    if (gender === 1) {
      return <ManOutlined style={{ color: '#1890ff' }} />;
    } else if (gender === 2) {
      return <WomanOutlined style={{ color: '#eb2f96' }} />;
    }
    return null;
  };

  // 获取等级标签
  const getPayGradeTag = (payGrade?: number) => {
    if (!payGrade || payGrade === 0) return null;
    return (
      <Tag color="gold" icon={<CrownOutlined />}>
        Lv.{payGrade}
      </Tag>
    );
  };

  // 获取粉丝团标签
  const getFansClubTag = (fansLevel?: number, fansClubName?: string) => {
    if (!fansLevel || fansLevel === 0) return null;
    return (
      <Tag color="red" icon={<HeartOutlined />}>
        {fansClubName || '粉丝团'} Lv.{fansLevel}
      </Tag>
    );
  };

  // 渲染消息内容
  const renderMessageContent = (record: Message) => {
    if (record.messageType === 'WebcastGiftMessage' && record.giftName) {
      return (
        <Space>
          <GiftOutlined style={{ color: '#faad14' }} />
          <Text strong style={{ color: '#faad14' }}>{record.giftName}</Text>
          {record.giftCount && <Text type="secondary">x{record.giftCount}</Text>}
          {record.giftValue && <Text type="warning">({record.giftValue}币)</Text>}
          {record.giftIcon && <Image src={record.giftIcon} width={24} height={24} preview={false} style={{ marginLeft: '4px' }} />}
        </Space>
      );
    }
    return (
      <Text style={{ fontSize: '14px' }}>
        {record.content}
      </Text>
    );
  };

  // 根据选择的类型显示提示
  const renderTypeHint = () => {
    if (filters.type === 'WebcastGiftMessage') {
      return (
        <div style={{ 
          marginBottom: '16px', 
          padding: '8px 16px', 
          background: '#fffbe6', 
          border: '1px solid #ffe58f',
          borderRadius: '4px'
        }}>
          <Space>
            <GiftOutlined style={{ color: '#faad14' }} />
            <Text>当前显示的是礼物消息，数据来自礼物记录接口</Text>
          </Space>
        </div>
      );
    }
    return null;
  };

  // 渲染列表项
  const renderListItem = (item: Message) => {
    const avatar = item.userAvatar ? (
      <Avatar 
        src={item.userAvatar} 
        size={48}
        style={{ border: item.userBorder ? `2px solid transparent` : 'none' }}
      />
    ) : (
      <Avatar size={48} icon={<UserOutlined />} />
    );

    return (
      <List.Item
        key={item.id}
        style={{ 
          padding: '16px 24px',
          borderBottom: '1px solid #f0f0f0',
          background: '#fff'
        }}
        actions={[
          <Popconfirm
            title="确定要删除这条消息吗？"
            onConfirm={() => handleDelete(item.id)}
            okText="确定"
            cancelText="取消"
          >
            <Button
              type="primary"
              danger
              size="small"
              icon={<DeleteOutlined />}
            >
              删除
            </Button>
          </Popconfirm>
        ]}
      >
        <List.Item.Meta
          avatar={avatar}
          title={
            <Space wrap>
              <Text strong style={{ fontSize: '16px' }}>
                {item.userName || '匿名用户'}
              </Text>
              {getGenderIcon(item.userGender)}
              {getPayGradeTag(item.payGrade)}
              {getFansClubTag(item.fansLevel, item.fansClubName)}
              {getMessageTypeTag(item.messageType)}
              <Text type="secondary" style={{ fontSize: '12px' }}>
                {dayjs(item.createdAt).format('MM-DD HH:mm:ss')}
              </Text>
            </Space>
          }
          description={
            <div style={{ marginTop: '8px' }}>
              {renderMessageContent(item)}
              <div style={{ marginTop: '8px', fontSize: '12px', color: '#999' }}>
                <Space split={<Divider type="vertical" />}>
                  <span>主播: {item.room?.streamerName || item.room?.title || item.roomId}</span>
                  <span>ID: {item.id.slice(-8)}</span>
                  {item.userId && <span>用户ID: {item.userId.slice(-8)}</span>}
                </Space>
              </div>
            </div>
          }
        />

      </List.Item>
    );
  };

  useEffect(() => {
    fetchRooms();
    fetchMessages({ page: 1, limit: getPaginationSize(PAGINATION_CONFIG.DEFAULT_PAGE_SIZE) });
  }, []);

  return (
    <div style={{ padding: '24px', display: 'flex', flexDirection: 'column', height: 'calc(100vh - 64px)' }}>
      <div style={{ marginBottom: '16px', display: 'flex', justifyContent: 'flex-end', alignItems: 'center' }}>
        <Space>
          <Button
            icon={<BarChartOutlined />}
            onClick={toggleStats}
            type={showStats ? 'primary' : 'default'}
          >
            {showStats ? '隐藏统计' : '显示统计'}
          </Button>
          <Button
            icon={<ReloadOutlined />}
            onClick={() => fetchMessages(filters)}
            loading={loading}
          >
            刷新
          </Button>
        </Space>
      </div>

      {/* 统计卡片 */}
      {showStats && stats && (
        <Row gutter={16} style={{ marginBottom: '16px' }}>
          <Col span={6}>
            <Card>
              <Statistic
                title="总消息数"
                value={stats.totalMessages}
                prefix={<MessageOutlined />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="礼物消息"
                value={stats.messagesByType.gift || 0}
                prefix={<GiftOutlined />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="聊天消息"
                value={stats.messagesByType.chat || 0}
                prefix={<MessageOutlined />}
              />
            </Card>
          </Col>
          <Col span={6}>
            <Card>
              <Statistic
                title="活跃用户"
                value={stats.activeUsers.length}
                prefix={<UserOutlined />}
              />
            </Card>
          </Col>
        </Row>
      )}

      {/* 搜索表单 */}
      <Collapse
        activeKey={searchCollapsed ? [] : ['searchForm']}
        onChange={() => setSearchCollapsed(!searchCollapsed)}
        style={{ marginBottom: '16px' }}
        expandIconPosition="end"
      >
        <Collapse.Panel 
          key="searchForm" 
          header={
            <div style={{ fontWeight: 'bold' }}>
              <SearchOutlined style={{ marginRight: '8px' }} />
              搜索条件
            </div>
          }
        >
          <Form
            form={form}
            layout="vertical"
            style={{ width: '100%' }}
          >
            <Row gutter={[16, 16]}>
              <Col xs={24} sm={12} md={8} lg={6}>
                <Form.Item name="roomId" label="房间">
                  <Select
                    placeholder="选择主播"
                    allowClear
                    showSearch
                    optionFilterProp="children"
                    onChange={handleRoomChange}
                  >
                    {rooms.map(room => (
                      <Option key={room.id} value={room.id}>
                        {room.streamerName || '未知主播'}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              
              <Col xs={24} sm={12} md={8} lg={6}>
                <Form.Item name="sessionId" label="直播场次">
                  <Select
                    placeholder="选择直播场次"
                    allowClear
                    showSearch
                    optionFilterProp="children"
                    loading={sessionsLoading}
                    disabled={!selectedRoomId}
                    onChange={handleFormChange}
                  >
                    {sessions.map(session => (
                      <Option key={session.id} value={session.id}>
                        {session.displayTitle}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              
              <Col xs={24} sm={12} md={8} lg={6}>
                <Form.Item name="type" label="消息类型">
                  <Select 
                    placeholder="选择消息类型" 
                    allowClear
                    onChange={handleFormChange}
                  >
                    {messageTypes.map(type => (
                      <Option key={type.value} value={type.value}>
                        {type.label}
                      </Option>
                    ))}
                  </Select>
                </Form.Item>
              </Col>
              
              <Col xs={24} sm={12} md={8} lg={6}>
                <Form.Item name="dateRange" label="时间范围">
                  <RangePicker
                    showTime
                    format="YYYY-MM-DD HH:mm:ss"
                    placeholder={['开始时间', '结束时间']}
                    onChange={handleFormChange}
                    style={{ width: '100%' }}
                  />
                </Form.Item>
              </Col>
              
              <Col xs={24} sm={12} md={8} lg={6}>
                 <Form.Item label="操作">
                   <Button onClick={handleReset} style={{ width: '100%' }}>
                     重置
                   </Button>
                 </Form.Item>
               </Col>
            </Row>
          </Form>
        </Collapse.Panel>
      </Collapse>

      {/* 内容区域 - 使用flex布局，并固定footer */}
      <div style={{ 
        display: 'flex', 
        flexDirection: 'column', 
        flex: 1, 
        overflow: 'hidden'
      }}>
        {/* 消息列表 - 可滚动区域 */}
        <div style={{ 
          flex: 1, 
          overflow: 'auto',
           
          background: '#fff'
        }}>
          {renderTypeHint()}
          <List
            dataSource={messages}
            loading={loading}
            renderItem={renderListItem}
            pagination={false}
            style={{ 
              background: '#fafafa',
              width: '100%'
            }}
          />
        </div>

        {/* 页脚 - 固定在底部 */}
        <div style={{ 
          padding: '16px 24px', 
          borderTop: '1px solid #f0f0f0', 
          background: '#fff',
          display: 'flex',
          justifyContent: 'space-between',
          alignItems: 'center',
          position: 'fixed',
          bottom: '24px',
          left: '24px',
          right: '24px',
          height: '64px',
          zIndex: 10,
          boxShadow: '0 -2px 8px rgba(0,0,0,0.09)'
        }}>
          <div>
            共 {pagination?.total || 0} 条记录，每页显示 {pagination?.pageSize || getPaginationSize(PAGINATION_CONFIG.DEFAULT_PAGE_SIZE)} 条
          </div>
          <Pagination
            current={pagination?.current || 1}
            pageSize={pagination?.pageSize || getPaginationSize(PAGINATION_CONFIG.DEFAULT_PAGE_SIZE)}
            total={pagination?.total || 0}
            pageSizeOptions={PAGINATION_CONFIG.PAGE_SIZE_OPTIONS}
            showSizeChanger={PAGINATION_CONFIG.SHOW_SIZE_CHANGER}
            showQuickJumper={PAGINATION_CONFIG.SHOW_QUICK_JUMPER}
            onChange={handleTableChange}
            onShowSizeChange={handlePageSizeChange}
          />
        </div>
      </div>
    </div>
  );
};

export default MessagePage;